package com.thinkit.bigdata.web.service.impl.bus;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.feature.orm.mybatis.Page;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.PropertiesUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.core.util.httpUtil.HttpUtil;
import com.thinkit.bigdata.core.util.thread.ThreadExecutorUtil;
import com.thinkit.bigdata.web.controller.bus.PerTaskThread;
import com.thinkit.bigdata.web.dao.bus.BusModelRuleMapper;
import com.thinkit.bigdata.web.dao.bus.BusWorkMapper;
import com.thinkit.bigdata.web.dao.bus.BusWorkModelMapper;
import com.thinkit.bigdata.web.dao.sys.SysConfigMapper;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.bus.*;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.service.bus.BusWorkService;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 *
 * Created by hccl on 2018/9/17.
 */
@Service
public class BusWorkServiceImpl implements BusWorkService {

    private static Logger logger = Logger.getLogger(BusWorkServiceImpl.class);

    @Resource
    private SysConfigMapper sysConfigMapper;

    @Resource
    private BusWorkMapper busWorkMapper;

    @Resource
    private BusWorkModelMapper busWorkModelMapper;

    @Resource
    private BusModelRuleMapper busModelRuleMapper;

    @Resource
    private ESUtil esUtil;

    @Override
    public BusWorkWithBLOBs selectByPrimaryKey(Long id) {
        return busWorkMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<BusWorkWithBLOBs> selectByExample(Page<BusWorkWithBLOBs> page, BusWorkExample example) {
        return busWorkMapper.selectByExampleWithBLOBs(page, example);
    }

    @Override
    public List<BusWorkWithBLOBs> selectByExample(BusWorkExample example) {
        return busWorkMapper.selectByExampleWithBLOBs(example);
    }

    @Override
    public int updateByPrimaryKey(BusWorkWithBLOBs record) {
        return busWorkMapper.updateByPrimaryKeyWithBLOBs(record);
    }

    @Override
    public List<Map<String, Object>> selectWorkInfos(Page page, Map<String,Object> paramsMap) {
        List<Map<String, Object>> workDtoList = busWorkMapper.selectWorkInfos(page, paramsMap);
        for (Map<String, Object> mapDto : workDtoList) {
            Map<String, Object> map = new HashMap<>();
            map.put("workId", mapDto.get("id"));
            mapDto.put("models", busModelRuleMapper.getRuleByTree(map));
        }
        return workDtoList;
    }

    @Override
    public List<Map<String, Object>> selectWorkInfos(Map<String, Object> paramsMap) {
        List<Map<String, Object>> workDtoList = busWorkMapper.selectWorkInfos(paramsMap);
        for (Map<String, Object> mapDto : workDtoList) {
            Map<String, Object> map = new HashMap<>();
            map.put("workId", mapDto.get("id"));
            mapDto.put("models", busModelRuleMapper.getRuleByTree(map));
        }
        return workDtoList;
    }

    @Override
    public List<BusWorkWithBLOBs> selectByCode(String code) {
        BusWorkExample example = new BusWorkExample();
        example.createCriteria().andProvincecodeEqualTo(code);
        return busWorkMapper.selectByExampleWithBLOBs(example);
    }

    @Override
    public BusWorkWithBLOBs getTaskByModelId(Long modelId) {
        BusWorkModelExample example = new BusWorkModelExample();
        example.createCriteria().andModelidEqualTo(modelId);
        List<BusWorkModel> bwms = busWorkModelMapper.selectByExample(example);
        if (bwms != null) {
            return busWorkMapper.selectByPrimaryKey(bwms.get(0).getWorkid());
        }
        return null;
    }

    @Override
    public HtmlResult getTaskExpiryDateByDelete(HttpServletRequest request) {
        String workIds = request.getParameter("id");
        String[] workIdArr = workIds.split(",");
        String modelName = request.getParameter("modelName");
        String[] modelNameArr = modelName.split(",");
        String workName = request.getParameter("workName");
        String[] workNameArr = workName.split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < workIdArr.length; i++) {
            if (getTaskExpiryDateNum(Long.parseLong(workIdArr[i])) > 0) {
                BusWork busWork = busWorkMapper.selectByPrimaryKey(Long.parseLong(workIdArr[i]));
                sb.append("模型【").append(modelNameArr[i]).append("】被质检任务【").append(workNameArr[i]).append("】使用，");
                sb.append("该任务").append(esUtil.changeTaskStatus(busWork.getProstatus())).append("在任务停止/完成后的").append(sysConfigMapper.selectByPrimaryKey(Constants.WORK_END_NON_DAY).getValue()).append("天内，不能删除模型").append("\n\n");
            }
        }
        if ("".equals(sb.toString())) {
            return HtmlResult.success();
        }
        return HtmlResult.failure(sb.toString());
    }

    @Override
    public int getTaskExpiryDateNum(Long id) {
        BusWork busWork = busWorkMapper.selectByPrimaryKey(id);
        int workEndNonDay = Integer.parseInt(sysConfigMapper.selectByPrimaryKey(Constants.WORK_END_NON_DAY).getValue());
        //TODO获取任务质检完成时间
        if (busWork.getStoptime() == null) {
            return workEndNonDay;
        }
        //获取可删除时间
        Date delDate = DateFormatUtil.addNDay(busWork.getStoptime(), workEndNonDay);
        //判断当前日期与可删除日期还差几天
        return DateFormatUtil.intervalDay(delDate, new Date());
    }

    @Override
    public HtmlResult insertSelective(HttpServletRequest request) {
        String provinceCodes = request.getParameter("provinceCode");//省份
        String workType = request.getParameter("workType");//任务分类
        String workName = request.getParameter("workName");//质检任务名称
        String scoreFlag = request.getParameter("scoreFlag");//质检任务名称
        String evalCycleStart = request.getParameter("evalCycleStart");//考核周期开始
        String evalCycleEnd = request.getParameter("evalCycleEnd");//考核周期截止
        String evalTimeStart = request.getParameter("evalTimeStart");//考核
        String evalTimeEnd = request.getParameter("evalTimeEnd");//考核
        String onHooks = request.getParameter("onHook");//挂机方
        String satisfaction = request.getParameter("satisfaction");//满意度
        String reCallFlag = request.getParameter("reCallFlag");//是否重复来电
        String minDuration = request.getParameter("minDuration");//语音最短时长
        String maxDuration = request.getParameter("maxDuration");//语音最长时长
        String description = request.getParameter("description");//任务描述
        String callStartTime = request.getParameter("callStartTime");//通话开始时间
        String callEndTime = request.getParameter("callEndTime");//通话结束时间
        String seatGroupIds = request.getParameter("seatGroupId");//被质检班组
        String seatIds = request.getParameter("seatIds");//被质检座席工号
        String customerlocs = request.getParameter("customerloc");//归属地
        String customerNums = request.getParameter("customerNum");//客户号码
        String customerLevels = request.getParameter("customerLevels");//客户星级
        String customerSign = request.getParameter("customerSign");//重点客户
        String callDirection = request.getParameter("callDirection");//呼叫类型
        String callTags = request.getParameter("callTags");//话务小结
        String sysTags = request.getParameter("sysTags");//系统标签
        String serialNumbers = request.getParameter("serialNumber");//录音流水
        String modelIds = request.getParameter("modelIds");//模型ID
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);

        BusWorkWithBLOBs busWork = new BusWorkWithBLOBs();
        busWork.setProvincecode(provinceCodes);
        busWork.setWorktype(Integer.parseInt(workType));
        busWork.setWorkname(workName);
        busWork.setScoreflag(Integer.parseInt(scoreFlag));
        busWork.setProstatus(BaseEntity.TASK_PROSTATUS_BEGIN);
        if (!Strings.isNullOrEmpty(callTags)) {
            busWork.setCalltags(callTags);
        }
        if (!Strings.isNullOrEmpty(sysTags)) {
            busWork.setSystags(sysTags);
        }
        if (!Strings.isNullOrEmpty(customerSign)) {
            busWork.setCustomersign(Integer.parseInt(customerSign));
        }
        if (!Strings.isNullOrEmpty(callDirection)) {
            busWork.setCalldirection(Integer.parseInt(callDirection));
        }
        if (!Strings.isNullOrEmpty(evalCycleStart)) {
            busWork.setEvalcyclestart(Integer.parseInt(evalCycleStart));
        }
        if (!Strings.isNullOrEmpty(evalCycleEnd)) {
            busWork.setEvalcycleend(Integer.parseInt(evalCycleEnd));
        }
        busWork.setFullscore(100);
        if (!Strings.isNullOrEmpty(minDuration)) {
            busWork.setMinduration(Double.parseDouble(minDuration));
        }
        if (!Strings.isNullOrEmpty(maxDuration)) {
            busWork.setMaxduration(Double.parseDouble(maxDuration));
        }
        busWork.setSatisfaction(satisfaction);
        if (!Strings.isNullOrEmpty(onHooks)) {
            busWork.setOnhooks(onHooks);
        }
        if (!Strings.isNullOrEmpty(reCallFlag)) {
            busWork.setRecallflag(Integer.parseInt(reCallFlag));
        }
        if (!Strings.isNullOrEmpty(customerLevels)) {
            busWork.setCustomerlevels(customerLevels);
        }
        busWork.setDescription(description);
        Date date = new Date();
        busWork.setCreatetime(date);
        busWork.setLastupdatetime(date);
        busWork.setCreateuserid(user.getId());
        if (BaseEntity.PREQUALITY_AUTO == Integer.parseInt(workType)) {
            busWork.setCallstarttime(DateFormatUtil.stringToDate(callStartTime, DateFormatUtil.yyyy_MM_dd));
            busWork.setCallendtime(DateFormatUtil.stringToDate(callEndTime, DateFormatUtil.yyyy_MM_dd));
        } else {
            busWork.setCallstarttime(DateFormatUtil.stringToDate(callStartTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
            busWork.setCallendtime(DateFormatUtil.stringToDate(callEndTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        busWork.setEvaltimestart(evalTimeStart);
        busWork.setEvaltimeend(evalTimeEnd);
        if (!Strings.isNullOrEmpty(seatGroupIds)) {
            busWork.setSeatgroupids(seatGroupIds);
        }
        busWork.setSeatids(seatIds);
        busWork.setCustomerloc(customerlocs);
        busWork.setCustomernums(customerNums);
        busWork.setSerialnumbers(serialNumbers);
        int add = busWorkMapper.insertSelective(busWork);
        logger.info("【添加质检任务】id = " + busWork.getId());
        if (add == 0) {
            return HtmlResult.failure("数据添加失败");
        }
        if (!Strings.isNullOrEmpty(modelIds)) {
            for (String id : modelIds.split(",")) {
                BusWorkModel busWorkModel = new BusWorkModel();
                busWorkModel.setWorkid(busWork.getId());
                busWorkModel.setModelid(Long.parseLong(id));
                busWorkModelMapper.insertSelective(busWorkModel);
            }
        }
        return HtmlResult.success("数据添加成功");
    }

    @Override
    public HtmlResult deleteByPrimaryKey(String ids) {
        for (String id : ids.split(",")) {
            if (busWorkMapper.deleteByPrimaryKey(Long.parseLong(id)) != 0) {
                BusWorkModelExample example = new BusWorkModelExample();
                example.createCriteria().andWorkidEqualTo(Long.parseLong(id));
                busWorkModelMapper.deleteByExample(example);
            }
        }
        return HtmlResult.success("删除数据成功");
    }

    @Override
    public HtmlResult updateByPrimaryKeySelective(HttpServletRequest request) {
        String id = request.getParameter("id");//任务id
        BusWorkWithBLOBs busWork = busWorkMapper.selectByPrimaryKey(Long.parseLong(id));
        if (busWork == null) {
            return HtmlResult.failure("没有此条数据");
        }
        String workName = request.getParameter("workName");//任务id
        //判断任务是否质检中
        if (busWork.getProstatus() == BaseEntity.TASK_PROSTATUS_TEST_ING) {
            busWork.setWorkname(workName);
            if (busWorkMapper.updateByPrimaryKeySelective(busWork) == 0) {
                return HtmlResult.failure("数据更新失败");
            }
            //TODO异步修改所有与该任务相关的es数据记录
            logger.info("异步修改所有与该任务相关的es数据记录");
            ThreadExecutorUtil.executeTask(new PerTaskThread(Long.parseLong(id), workName, esUtil));
            return HtmlResult.success("数据更新成功");
        }
        BusWorkModelExample example = new BusWorkModelExample();
        example.createCriteria().andWorkidEqualTo(Long.parseLong(id));
        busWorkModelMapper.deleteByExample(example);
        String modelIds = request.getParameter("modelIds");//任务id
        if (!Strings.isNullOrEmpty(modelIds)) {
            for (String modelId : modelIds.split(",")) {
                BusWorkModel busWorkModel = new BusWorkModel();
                busWorkModel.setWorkid(Long.parseLong(id));
                busWorkModel.setModelid(Long.parseLong(modelId));
                busWorkModelMapper.insertSelective(busWorkModel);
            }
        }
        String provinceCodes = request.getParameter("provinceCode");//任务id
        String workType = request.getParameter("workType");//任务id
        String scoreFlag = request.getParameter("scoreFlag");//任务id
        String minDuration = request.getParameter("minDuration");//语音最短时长
        String maxDuration = request.getParameter("maxDuration");//语音最长时长
        String evalCycleStart = request.getParameter("evalCycleStart");//任务id
        String evalCycleEnd = request.getParameter("evalCycleEnd");//任务id
        String evalTimeStart = request.getParameter("evalTimeStart");//考核
        String evalTimeEnd = request.getParameter("evalTimeEnd");//考核
        String onHooks = request.getParameter("onHook");//挂机方
        String satisfaction = request.getParameter("satisfaction");//满意度
        String reCallFlag = request.getParameter("reCallFlag");//是否重复来电
        String description = request.getParameter("description");//任务id
        String callStartTime = request.getParameter("callStartTime");//任务id
        String callEndTime = request.getParameter("callEndTime");//任务id
        String seatGroupIds = request.getParameter("seatGroupId");//任务id
        String seatIds = request.getParameter("seatIds");//任务id
        String customerlocs = request.getParameter("customerloc");//归属地
        String customerNums = request.getParameter("customerNum");//任务id
        String customerLevels = request.getParameter("customerLevels");//任务id
        String customerSign = request.getParameter("customerSign");//重点客户
        String callDirection = request.getParameter("callDirection");//呼叫类型
        String callTags = request.getParameter("callTags");//话务小结
        String sysTags = request.getParameter("sysTags");//系统标签
        String serialNumbers = request.getParameter("serialNumber");//任务id
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
        busWork.setEvaltimestart(evalTimeStart);
        busWork.setEvaltimeend(evalTimeEnd);
        busWork.setScoreflag(Integer.parseInt(scoreFlag));
        busWork.setProvincecode(provinceCodes);
        if (!Strings.isNullOrEmpty(callTags)) {
            busWork.setCalltags(callTags);
        } else {
            busWork.setCalltags(null);
        }
        if (!Strings.isNullOrEmpty(sysTags)) {
            busWork.setSystags(sysTags);
        } else {
            busWork.setSystags(null);
        }
        if (!Strings.isNullOrEmpty(customerSign)) {
            busWork.setCustomersign(Integer.parseInt(customerSign));
        } else {
            busWork.setCustomersign(null);
        }
        if (!Strings.isNullOrEmpty(callDirection)) {
            busWork.setCalldirection(Integer.parseInt(callDirection));
        } else {
            busWork.setCalldirection(null);
        }
        if (!Strings.isNullOrEmpty(workType)) {
            busWork.setWorktype(Integer.parseInt(workType));
        }
        if (!Strings.isNullOrEmpty(minDuration)) {
            busWork.setMinduration(Double.parseDouble(minDuration));
        } else {
            busWork.setMinduration(null);
        }
        if (!Strings.isNullOrEmpty(maxDuration)) {
            busWork.setMaxduration(Double.parseDouble(maxDuration));
        } else {
            busWork.setMaxduration(null);
        }
        busWork.setWorkname(workName);
        if (!Strings.isNullOrEmpty(evalCycleStart)) {
            busWork.setEvalcyclestart(Integer.parseInt(evalCycleStart));
        }
        if (!Strings.isNullOrEmpty(evalCycleEnd)) {
            busWork.setEvalcycleend(Integer.parseInt(evalCycleEnd));
        }
        if (!Strings.isNullOrEmpty(satisfaction)) {
            busWork.setSatisfaction(satisfaction);
        } else {
            busWork.setSatisfaction(null);
        }
        if (!Strings.isNullOrEmpty(onHooks)) {
            busWork.setOnhooks(onHooks);
        } else {
            busWork.setOnhooks(null);
        }
        if (!Strings.isNullOrEmpty(reCallFlag)) {
            busWork.setRecallflag(Integer.parseInt(reCallFlag));
        } else {
            busWork.setRecallflag(null);
        }
        if (!Strings.isNullOrEmpty(customerlocs)) {
            busWork.setCustomerloc(customerlocs);
        } else {
            busWork.setCustomerloc(null);
        }
        busWork.setDescription(description);
        if (!Strings.isNullOrEmpty(callStartTime)) {
            if (BaseEntity.PREQUALITY_AUTO == Integer.parseInt(workType)) {
                busWork.setCallstarttime(DateFormatUtil.stringToDate(callStartTime, DateFormatUtil.yyyy_MM_dd));
            } else {
                busWork.setCallstarttime(DateFormatUtil.stringToDate(callStartTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
            }
        }
        if (!Strings.isNullOrEmpty(callEndTime)) {
            if (BaseEntity.PREQUALITY_AUTO == Integer.parseInt(workType)) {
                busWork.setCallendtime(DateFormatUtil.stringToDate(callEndTime, DateFormatUtil.yyyy_MM_dd));
            } else {
                busWork.setCallendtime(DateFormatUtil.stringToDate(callEndTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
            }
        }
        if (!Strings.isNullOrEmpty(seatGroupIds)) {
            busWork.setSeatgroupids(seatGroupIds);
        } else {
            busWork.setSeatgroupids(null);
        }
        busWork.setSeatids(seatIds);
        busWork.setCustomernums(customerNums);
        busWork.setCustomerlevels(customerLevels);
        busWork.setSerialnumbers(serialNumbers);
        busWork.setLastupdatetime(new Date());
        busWork.setLastupdateuserid(user.getId());
        if (busWorkMapper.updateByPrimaryKeyWithBLOBs(busWork) == 0) {
            return HtmlResult.failure("数据更新失败");
        }
        return HtmlResult.success("数据更新成功");
    }

    private static String formatMonth(Integer moth) {
        if (moth.toString().length() == 1) {
            return "0" + moth;
        }
        return moth.toString();
    }

    @Override
    public HtmlResult startTask(HttpServletRequest request) throws IOException {
        String workIds = request.getParameter("id");//任务id
        Integer startOrStop = Integer.parseInt(request.getParameter("startOrStop"));//启动/停止
        String sOs = startOrStop == 0?"停止" : "启动";
        StringBuilder successSb = new StringBuilder();
        StringBuilder errorSb = new StringBuilder();
        StringBuilder allSb = new StringBuilder();
        for (String workId : workIds.split(",")) {
            BusWorkWithBLOBs busWork = busWorkMapper.selectByPrimaryKey(Long.parseLong(workId));
            if (busWork == null) {
                errorSb.append("没有ID = ").append(workId).append("的任务").append("\n\n");
                allSb.append("没有ID = ").append(workId).append("的任务").append("\n\n");
                continue;
            }
            Date date = new Date();
            if (busWork.getWorktype() == BaseEntity.PREQUALITY_AUTO) {//自动质检任务
                if (startOrStop == 1) {
                    Calendar dateCal = Calendar.getInstance();
                    dateCal.setTime(date);
                    int year =  dateCal.get(Calendar.YEAR);
                    int month = dateCal.get(Calendar.MONTH) + 1;
                    Date date1 = DateFormatUtil.stringToDate(year + "-" + formatMonth(month) + "-" + busWork.getEvalcyclestart() + " " + busWork.getEvaltimestart() + ":00", DateFormatUtil.yyyy_MM_dd_HH_mm_ss);
                    if (date.getTime() > date1.getTime()) {
                        date1 = DateFormatUtil.stringToDate(year + "-" + formatMonth(month+1) + "-" + busWork.getEvalcyclestart() + " " + busWork.getEvaltimestart() + ":00", DateFormatUtil.yyyy_MM_dd_HH_mm_ss);
                    }
                    busWork.setOnsettime(DateFormatUtil.addMinute(date1, -1));
                } else {
                    busWork.setStoptime(new Date());
                }
            } else if (busWork.getWorktype() == BaseEntity.PREQUALITY_PRE) {//预质检
                Map<String, Object> param = new HashMap<>();
                param.put("workId", busWork.getId());
                param.put("flag", busWork.getWorktype());
                param.put("isStart", startOrStop);
                String response = HttpUtil.sendJsonHttpPost(PropertiesUtil.getProperty("sendTaskToDispatch"), JSONObject.fromObject(param).toString());
                logger.info("【启动质检任务】质检任务" +sOs + "请求接口返回值" + response);
                JSONObject classify = JSONObject.fromObject(response);
                int rtnCode = classify.getInt("rtnCode");
                if (rtnCode != 0) {
                    errorSb.append("任务[").append(busWork.getWorkname()).append("]").append("由于").append(classify.getString("rtnMsg"))
                            .append(startOrStop).append("失败,").append("\n\n");
                    allSb.append("任务[").append(busWork.getWorkname()).append("]").append(classify.getString("rtnMsg"))
                            .append(startOrStop).append("失败,").append("\n\n");
                    continue;
                }
                if (startOrStop == 1) {
                    busWork.setOnsettime(date);
                } else {
                    busWork.setStoptime(new Date());
                }
            }
            busWork.setTotalnumber(null);
            busWork.setProstatus(startOrStop);
            busWork.setLastupdatetime(date);
            User user = (User) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
            busWork.setLastupdateuserid(user.getId());
            busWork.setLastupdatetime(date);
            if (busWorkMapper.updateByPrimaryKeySelective(busWork) == 0) {
                errorSb.append("任务[").append(busWork.getWorkname()).append("]").append(startOrStop).append("失败").append("\n\n");
                allSb.append("任务[").append(busWork.getWorkname()).append("]").append(startOrStop).append("失败").append("\n\n");
                continue;
            }
            successSb.append("任务[").append(busWork.getWorkname()).append("]").append(startOrStop).append("成功").append("\n\n");
            allSb.append("任务[").append(busWork.getWorkname()).append("]").append(startOrStop).append("成功").append("\n\n");
        }
        if (Strings.isNullOrEmpty(successSb.toString())) {
            return HtmlResult.failure(errorSb.toString());
        } else if (Strings.isNullOrEmpty(errorSb.toString())) {
            return HtmlResult.success(successSb.toString());
        }
        return HtmlResult.tips(allSb.toString());
    }
}
